package lupita.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lupita.model.vos.FileSystemItem;
import lupita.persistence.MySQLImpl;

/**
 * Servlet implementation class RecomendacionSvt
 */
public class Top5Svt extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MySQLImpl mysql;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Top5Svt() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		List<FileSystemItem> listFileRepo = (List<FileSystemItem>) session.getAttribute("fileRepoList");
		int userID = (Integer)session.getAttribute("IdUser");
		
		
		// se prepara el writer para la respuesta
		PrintWriter out = response.getWriter();
		
		// el voto del usuario
		Long top5 = Long.parseLong(request.getParameter("top5"));
		//Long top5 = Long.parseLong("5");
		
		// indice del archivo en la lista
		int index = Integer.parseInt(request.getParameter("fileindex"));
		//int index = Integer.parseInt("2");
		
		FileSystemItem fileRepo = listFileRepo.get(index);
		String fileRepoName = fileRepo.getFileName();
		String filePath = fileRepo.getFullPath();
		
		System.out.println("idFile: " + fileRepo.getId());
		
		//sustituir por una conexion sencilla
		//FileRepo findFileRepo = fileRepoDAO.findByName(fileRepoName);

		// si se encontro en la BD
		
		
		//SortedMap<String, String,String> file =  new TreeMap<String, String,String>(java.util.Collections.reverseOrder()) ;
		
		
		try {
			mysql = new MySQLImpl();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ResultSet result;
		ResultSet resultMax;
		ResultSet resultRating;
		ResultSet resultFR;
		int resultInsert;
		int idsFiles = 0;
		try{
			mysql.openConnection();
			/*
			String queryMax = "select MAX(id) as ids FROM file ";
			System.out.println("query" + queryMax);
			resultMax=  mysql.selectSQL(queryMax);
			if(resultMax.next()){
				if(resultMax.getString("ids") != null){
					idsFiles = Integer.parseInt(resultMax.getString("ids"));
				}else{
					idsFiles = 1;
				}
			}else{
				idsFiles = 1;
			}*/
			
			//consulto el archivo por nombre
			String query = "select * FROM file WHERE name = '"+ fileRepoName + "'";
			System.out.println("query" + query);
			result=  mysql.selectSQL(query);
			
			
		

			//System.out.println("max : " + resultMax);
			
			//result.beforeFirst();
		
			System.out.println("TABLA File");
		
			int fileID = 0;
			String fileName;	
			String path; 
			Long countRating = 0L;
			int resRating = 0;
			int top5Id = 0;
			int idr = 0;
						
			System.out.println("result: " + result);
		
			if(result.next()) {//obtengo datos del archivo almacenado
				fileID = result.getInt("id");
				fileName = result.getString("name");
				path = result.getString("path");
			
				System.out.println(fileID+" "+fileName+" "+path);
				//users.put(userID,user );
			}else{//pregunto si el archivo NO esta almacenado
				query = "INSERT INTO file (name,path) VALUES ('"+ fileRepoName + "'"+ ",'"+ filePath + "')";
				System.out.println("queryinsrt" + query);
				resultInsert =  mysql.execQuery(query);
				
				System.out.println("resultado del insert: " + resultInsert);
				/*
				query = "INSERT INTO file (name,path) VALUES ('"+ fileRepoName + "'"+ ",'"+ filePath + "')";
				System.out.println("queryinsrt" + query);
				resultInsert =  mysql.execQuery(query);
				*/
				//consulto el archivo despues de insertarlo para obtener su id
				query = "select * FROM file WHERE name = '"+ fileRepoName + "'";
				System.out.println("query" + query);
				result=  mysql.selectSQL(query);
				if(result.next()) {
					fileID = result.getInt("id");
					fileName = result.getString("name");
					path = result.getString("path");
				
					System.out.println(fileID+" "+fileName+" "+path);
					//users.put(userID,user );
				}
			}
			//si esta almacenado , preguntar si ya esta su reinting
			//query = "select r.rate as rat,r.id as idr from filerating fr join rating r on fr.idRating = r.id where fr.idFile = "+ fileID + "";
			query = "select r.votos as top5,r.id as idr from filetop5 fr join top5 r on fr.idTop5 = r.id where fr.idFile = "+ fileID;
			System.out.println("queryreputacion" + query);
			resultRating=  mysql.selectSQL(query);
			
			if(resultRating.next()){//pregunto si hay un registro
				countRating =  Long.parseLong(resultRating.getString("top5"));
				idr =  Integer.parseInt(resultRating.getString("idr"));
				
				query = "UPDATE top5 set votos = "+(countRating + top5)+" WHERE id="+idr;
				System.out.println("queryinsrt" + query);
				resultInsert =  mysql.execQuery(query);
				if(resultInsert == 1) {
					query = "select * FROM filetop5 WHERE idUser = "+ userID ;
					System.out.println("query" + query);
					resultFR=  mysql.selectSQL(query);
					if(resultFR.next()){
					}else{

						query = "INSERT INTO filetop5 (idTop5,idUser,idFile) VALUES ("+idr+","+userID+","+fileID+")";
						System.out.println("queryinsrt" + query);
						int resFileRating =  mysql.execQuery(query);
						System.out.println("resFileRating: "+resFileRating);
					}
				}
				
			}else{//se almacena el rating por primera vez con el usuario y el id del archivo
				query = "INSERT INTO top5 (votos) VALUES ("+top5+")";
				System.out.println("queryinsrt" + query);
				resRating =  mysql.execQuery(query);
				query = "select MAX(id) as id FROM top5 ";
				System.out.println("query" + query);
				result=  mysql.selectSQL(query);
				if(result.next()) {
					top5Id = result.getInt("id");
					System.out.println("resReputacion: "+resRating);
					if(resRating == 1){
						query = "INSERT INTO filetop5 (idTop5,idUser,idFile) VALUES ("+top5Id+","+userID+","+fileID+")";
						System.out.println("queryinsrt" + query);
						int resFileRating =  mysql.execQuery(query);
						System.out.println("resFileRating: "+resFileRating);
					
					}
				}
			}
				
			
		
			mysql.closeConnection();
			
			out.println("succes-");
		
		}catch(Exception e){
			e.printStackTrace();
		}
		
		//request.setAttribute("users", users);

	}

}
